package com.github.ecbp.common.utils.excel.utils;

import com.alibaba.excel.context.AnalysisContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;

/**
 * 简单的默认excel文件处理回调, 用户可根据自己需要继承ExcelOperationListener实现
 */
public class ExcelDefaultOperationListener<T> extends AbstractExcelOperationListener<T> {
    protected final Logger logger = LoggerFactory.getLogger(this.getClass());

    public ExcelDefaultOperationListener() {
        super.setHeadNumber(0);
    }

    public ExcelDefaultOperationListener(int headNumber) {
        super.setHeadNumber(headNumber);
    }

    /**
     * 每隔5条存储数据库，实际使用中可以3000条，然后清理list ，方便内存回收
     */
    private static final int BATCH_COUNT = 5;
    List<T> list = new ArrayList<>();
    private int count = 0;

    @Override
    public void invoke(T data, AnalysisContext context) {
        logger.info("解析到一条数据:{ " + data.toString() + " }");
        list.add(data);
        count++;
        if (list.size() >= BATCH_COUNT) {
            saveData(count);
            list.clear();
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        saveData(count);
        logger.info("所有数据解析完成！ count ：" + count);
    }

    /**
     * 加上存储数据库
     */
    private void saveData(int count) {
        // database ...
        logger.info("{ " + count + " }条数据，开始存储数据库！" + list.size());
        logger.info("存储数据库成功！");
    }

    public List<T> getList() {
        return list;
    }
}
